package com.yoomiito.app.present.cicle;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.JsonArray;
import com.yoomiito.app.base.AppConfig;
import com.yoomiito.app.base.BaseActPresenter;
import com.yoomiito.app.model.cicle.CicleProductnfo;
import com.yoomiito.app.model.cicle.ImageBean;
import com.yoomiito.app.model.cicle.QiniuTokenInfo;
import com.yoomiito.app.net.UploadFileManager;
import com.yoomiito.app.net.YmApi;
import com.yoomiito.app.ui.cicle.CiclePublishActivity;
import com.yoomiito.app.utils.NetworkUtils;
import com.yoomiito.app.utils.YMToast;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import cn.droidlover.xdroidmvp.net.ApiException;
import cn.droidlover.xdroidmvp.net.ApiSubscriber;
import cn.droidlover.xdroidmvp.net.XApi;

public class CiclePublishPresenter extends BaseActPresenter<CiclePublishActivity> {

    private String productId;
    private String orderId;
    private int goodsType = -1;
    private QiniuTokenInfo mQiniuToken;
    private String mCurrentPhotoPath;

    public String getmCurrentPhotoPath() {
        return mCurrentPhotoPath;
    }

    public void setmCurrentPhotoPath(String mCurrentPhotoPath) {
        this.mCurrentPhotoPath = mCurrentPhotoPath;
    }

    public CiclePublishPresenter(AppConfig appConfig) {
        super(appConfig);
    }

//    private CicleProductnfo productnfo;

    public String getProductId() {
        return productId;
    }

    public void setProductId(String productId) {
        this.productId = productId;
    }

    public String getOrderId() {
        return orderId;
    }

    public void setOrderId(String orderId) {
        this.orderId = orderId;
    }

    public int getGoodsType() {
        return goodsType;
    }

    public void setGoodsType(int goodsType) {
        this.goodsType = goodsType;
    }

    public void getProductInfoData(){
        if (NetworkUtils.checkNetPermission(getV())){
            return;
        }
        YmApi.getYmService()
                .geProductInfoData(productId,orderId,goodsType)
                .compose(getV().bindToLifecycle())
                .compose(XApi.<CicleProductnfo>getApiTransformerData())
                .compose(XApi.<CicleProductnfo>getScheduler())
                .subscribe(new ApiSubscriber<CicleProductnfo>() {
                    @Override
                    public void onSuccess(CicleProductnfo data) {
//                         productnfo = data;
                         getV().setmBuyGoodsData(data);
                    }

                    @Override
                    public void onFail(ApiException error) {
                        YMToast.showText("error");
                    }
                });
    }

    public void publishCicle(){
        if (NetworkUtils.checkNetPermission(getV())){
            return;
        }
        JsonArray jsonArray = new JsonArray();
        for (ImageBean item : getV().imageBeanList){
            if (!item.isAdd()){
                jsonArray.add(item.getUrl());
            }
        }
        String imageUrlPublish = jsonArray.toString();
        String content = getV().mContentEt.getText().toString();
        int type = getV().publishType;
        YmApi.getYmService()
                .publishCicle(productId,orderId,goodsType,content,imageUrlPublish,type)
                .compose(getV().bindToLifecycle())
                .compose(XApi.<Object>getApiTransformerData())
                .compose(XApi.<Object>getScheduler())
                .subscribe(new ApiSubscriber<Object>() {
                    @Override
                    public void onSuccess(Object data) {
                        getV().dismissLoading();
                        YMToast.showText("发布成功");
                        getV().setResult(CiclePublishActivity.CODE_PUBLISH_CICLE);
                        getV().finish();
                    }

                    @Override
                    public void onFail(ApiException error) {
                        getV().dismissLoading();
//                        YMToast.showText("error");
                        if (3001==error.getCode()){
                            getV().showTip(error.getMsg());
                        }
                    }
                });
    }

    public void uploadPhotos(final int index) {
        if (getV().imageBeanList != null) {
            if (index == 0) {
//                YMToast.showText("开始上传");
//                getView().showLoadingView("上传中...");
            }
            ImageBean tempUploadPhotoBean = getV().imageBeanList.get(index);
            if (tempUploadPhotoBean != null
                    && !tempUploadPhotoBean.isAdd()
                    && tempUploadPhotoBean.isLocalImage()
                    && TextUtils.isEmpty(tempUploadPhotoBean.getUrl())
                    && !TextUtils.isEmpty(tempUploadPhotoBean.getImagePath())) {
                UploadFileManager.uploadFile(tempUploadPhotoBean.getImagePath(), "" + index, new UploadFileManager.UploadFileCallBack() {
                    @Override
                    public void uploadSucc(String filename, String key) {
                        Log.e("lin", "imageUrl-->" + filename);
                        getV().imageBeanList.get(Integer.parseInt(key)).setUrl(filename);
                        if (index >= getV().imageBeanList.size() - 1) {
                            uploadPhotosOk();
                        } else {
                            uploadPhotos(index + 1);
                        }
                    }

                    @Override
                    public void uploadFail(int code, String key) {
//                        if (getView() != null) {
//                            getView().dissmissLoadingView();
//                        }
                        getV().dismissLoading();
                        YMToast.showText("上传失败");
                    }
                });
            } else {
                if (index >= getV().imageBeanList.size() - 1) {
                    uploadPhotosOk();
                } else {
                    uploadPhotos(index + 1);
                }
            }
        }
    }

    private void uploadPhotosOk(){
//        YMToast.showText("上传完成");
        publishCicle();
    }

    public void takeCamera(int num) {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Ensure that there's a camera activity to handle the intent
        if (takePictureIntent.resolveActivity(getV().getPackageManager()) != null) {
            // Create the File where the photo should go
            File photoFile = null;
            photoFile = createImageFile();
            // Continue only if the File was successfully created
            if (photoFile != null) {
//                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
//                        Uri.fromFile(photoFile));
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                        getImageContentUri(photoFile));

            }
        }

        getV().startActivityForResult(takePictureIntent, num);//跳转界面传回拍照所得数据
    }
    private File createImageFile() {
        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        File image = null;
        try {
            image = File.createTempFile(
                    generateFileName(),  /* prefix */
                    ".jpg",         /* suffix */
                    storageDir      /* directory */
            );
        } catch (IOException e) {
            e.printStackTrace();
        }

        mCurrentPhotoPath = image.getAbsolutePath();
        return image;
    }

    public static String generateFileName() {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        return imageFileName;
    }

    public Uri getImageContentUri(File imageFile) {
        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = getV().getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[] { MediaStore.Images.Media._ID },
                MediaStore.Images.Media.DATA + "=? ",
                new String[] { filePath }, null);

        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor
                    .getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (imageFile.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, filePath);
                return getV().getContentResolver().insert(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }

}
